/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.soa.util.wx;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author lianzuotai
 */
public class FileConnect {

    private final Logger log = LoggerFactory.getLogger(FileConnect.class);
    /**
     * http连接对象
     */
    private URL url;
    /**
     * http连接对象
     */
    private URLConnection con;
    /**
     * 超时时间
     */
    private static final int TIMEOUT = 10000;

    /**
     *
     * @param url
     */
    public FileConnect(String url) throws IOException {
        this(url, TIMEOUT);
    }

    /**
     *
     * @param url
     * @param timeout 超时时间
     */
    public FileConnect(String serverUrl, int timeout) throws IOException {
        log.debug("创建下载任务:{}", serverUrl);
        url = new URL(serverUrl);
        con = url.openConnection();
        con.setConnectTimeout(timeout);
        con.setReadTimeout(timeout);
    }

    /**
     * 下载文件
     * @param dirName 目录
     * @param fileName 文件名
     */
    public void downFile(String dirName, String fileName) {
        log.debug("开始下载下载文件:{}/{}", dirName, fileName);
        File dirFile = new File(dirName);
        if (!dirFile.isDirectory()) {
            dirFile.mkdirs();
        }
        File file = new File(dirFile, fileName);
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(con.getInputStream());
            byte[] buf = new byte[10240];
            int len = 0, sum = 0;
            bos = new BufferedOutputStream(new FileOutputStream(file));
            while ((len = bis.read(buf)) > 0) {
                sum += len;
                bos.write(buf, 0, len);
                log.debug("文件 {} 下载了 {} bytes...", fileName, sum);
            }
        } catch (IOException e) {
            log.debug("文件 {} 下载失败", fileName);
            log.error("文件下载异常:", e);
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (Exception e) {
                }
            }
            if (bos != null) {
                try {
                    bos.close();
                } catch (Exception e) {
                }
            }
        }
    }

    public static void main(String[] args) throws IOException {
//        String accessToken = "niI1w8Jh3JQH6dqoxj6thys8USJnsOVBGfrElXfcGslOXFOQAf_788zqiGNqVWu3YE8lVizw0GLiQpv2ZZzxQW4bylrlRb3cgCq9_quxApvX4RxnxrDlKigOVPxV-CNLHSMdABAVGA";
//        String mediaId = "wMXDCIiPDzgoYOJLsRBmV4z1gE4dw1q4E6LlraOsGR4bww2583S76qErw_wLTNQB";
//        String type = "jpg";
//        String url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token={}&media_id=";
//        FileConnect fc = new FileConnect(url.replace("{}", accessToken) + mediaId);
//        fc.downFile("/Users/lianzuotai/workspaces/down", mediaId + "." + type);

        File f = new File("/Users/lianzuotai/workspaces/down" + File.separator + "voice");
        f.mkdirs();
    }

}
